<script setup>
/**
 * @name 数字人字幕生成--列表 
 */
import { onMounted, reactive, ref,createVNode, onUnmounted } from 'vue'
import request from "@/common/utils/request";

import {
  QuestionCircleOutlined,
  PlayCircleOutlined,
  PauseCircleOutlined,
  FolderOutlined,
  DeleteOutlined,
  SwapOutlined,
  UnorderedListOutlined,
  CloudUploadOutlined,
  EyeOutlined,
  InfoCircleOutlined,
  ExclamationCircleOutlined,
  CustomerServiceOutlined,
  RedoOutlined,
  SaveOutlined,
  EllipsisOutlined
} from "@ant-design/icons-vue";

// 视频文件
import MaterialsModule from "@/views/shotstack/components/MaterialsModule/index.vue";
import { message, Empty, Modal} from 'ant-design-vue';
const materials = ref(null);

// 预览抽屉
import HumanSyntheticRecord from './HumanSyntheticRecord.vue'
const HumanSyntheticRecordRef = ref();

const emit = defineEmits(['viewVideo'])
const state = reactive({
    // 列表数据
  dataSource: [],
  // 筛选数据
  serchData: {},
  serchValue: {},
  
  // 是否已经挂载
  isInit: false,
  // 日期绑定数据
  time: [],
  // 保存的项
  saveItem: null,
  // 保存到成片库: true; 保存到素材库:false
  isFlaking: false,
  // 保存到素材库的开关
  saveVisible: false,
})

// 数字人生成状态筛选列表
const statusOptions = ref([])

// status:0待合成 1准备中 2合成中
const notOkStatus = [
  0, 1, 2
]

const formState = reactive({
  page: 1,
  pageSize: 20,
  total:0,
  start_time: '',
  end_time: '',
  name:''
})

const getStates = async () => {
  const res = await request.get(
    "/work_ai",
    "/digital/human/required/information"
  );
  console.log(res, "筛选字段");
  state.serchData = res.result;
  // 搜索框使用 需要删除 humanStatus
  statusOptions.value = res.result?.humanStatus?.select
  statusOptions.value.length && statusOptions.value.unshift({
    label: "全部状态",
    value: "all", 
  })
  res?.result?.humanStatus && delete res.result.humanStatus;

  console.log(state.serchData, "state.serchData");


  for (let key in res.result) {
    const item = state.serchData[key];
    if (item.type == "select") {
      item.select.unshift({
        label: key == "type" ? "全部模型" : "全部状态",
        value: "all",
      });
      state.serchValue[key] = "all";
    } else if (item.type == "text") {
      state.serchValue[key] = "";
    }
  }
};

//查看视频
const toviewVideo = (item) => {
  console.log(item, '查看组');
  const someOk = item.human_video_group_detail.some(ele => ele.status == 3)

  if(!someOk) {
    message.warning('视频正在生成中，请稍后查看')
    return 
  }
  HumanSyntheticRecordRef.value?.open(item)
};

// 拿到选择的文件夹等信息
const selfRequest = async (data) => {
  console.log(data);
  const params = {
    ai_asr_id: state.saveItem.id,
    merchant_folder_statck_id: data?.merchant_folder_statck_id,
    // 保存素材库 固定值为backend
    upload_from: state.isFlaking ? "" : "backend",
  };
  console.log(params, "接口参数");

  try {
    const res = await request.post(
      "/work_ai",
      "/human/video/media/aiAsr/save",
      params
    );
    if (res?.code && res.code != 1000) throw new Error(res.msg);
    console.log(res, "保存成功");
    message.success("保存成功");
  } catch (error) {
    message.error(error.message || "保存失败");
  } finally {
      materials.value.stopLoding();
      state.saveVisible = false;
  }
};

const resetSerch = () => {
  Object.assign(formState, {
    page: 1,
    pageSize: 20,
    start_time: '',
    end_time: '',
    name:''
  })
  state.time = []
  getList()
}

const timerId = ref(null)
const getList = async () => {

  if (timerId.value) {
    clearTimeout(timerId.value)
    timerId.value = null
  }

  console.log('getList 执行了');
  formState.start_time = state.time?.[0]??''
  formState.end_time = state.time?.[1]??''
  const params = {
    ...formState
  }

  // 0 - 待执行 1-成功 2-失败
  const res = await request.get(
    "/work_ai",
    "/digital/human/video/group/get",
    params
  );

  console.log(res,'数字人列表');
  state.dataSource = res?.result?.data ?? []
  formState.total = res?.result.total

  if (Array.isArray(res?.result?.data) && res.result.data.length) {
    const polling = res.result.data.some(ele => ele.human_video_group_detail.some(item => notOkStatus.includes(item.status)))
    polling && (
      timerId.value = setTimeout(() => {
        getList()
      },4000)
    )
  }
}

// 判断展示的主体内容
const cardShowMain = (item) => {
  const findImg = item?.human_video_group_detail.find(ele => ele.cover_url)
  if (findImg) {
    return {
      type: 'img',
      img: findImg.cover_url
    }
  }

  const findVideo = item?.human_video_group_detail.find(ele => ele.video_url)
  if (findVideo) {
    return {
      type: 'video',
      video: findVideo.video_url
    }
  }

  return {
    type: 'empty',
  }

} 

// 获取各状态的数量
const getStatusNumber = (params={}) => {
  const {item, status} = params 
  let arr
  if (status == '成功') {
    arr = item.human_video_group_detail.filter(ele => ele.status == 3)
  } else if (status == '失败') {
    arr = item.human_video_group_detail.filter(ele => ele.status == 4)
  } else {
    arr = item.human_video_group_detail.filter(ele => ele.status != 4 && ele.status != 3)
  }
  return arr.length
}

onMounted(() => {
  state.isInit = true
  getStates()
  getList()
})

// 离开页面, 清除定时器
onUnmounted(() => {
  timerId.value && clearTimeout(timerId.value);
});

const updateList = () => {
  if (state.isInit) {
    getList()
  }
}
 
defineExpose({
  updateList
})

</script>

<template>
    <div class="subtitleCreat">
      <div class="list_conent">
        <div class="serch_title" v-if="false">
          <div class="serch_left">
            <div class="serch_item" v-for="(value, key) in state.serchData" :key="key">
              <template v-if="value.type == 'text'">
                <a-input allow-clear @change="(e) => e.type == 'click' && serchChange()" style="width: 229px"
                  v-model:value="state.serchValue[key]" placeholder="请输入任务名称">
                  <template #prefix>
                    <SearchOutlined />
                  </template>
                </a-input>
             
              </template>

              <template v-if="value.type == 'select'">
                <div class="serch_item">
                  <a-select :field-names="{
                      label: 'label',
                      value: 'value',
                      options: 'children',
                    }" style="width: 200px" v-model:value="state.serchValue[key]" :filter-option="false"
                    @change="serchChange" :placeholder="'请选择' + value.label" :options="value.select">
                  </a-select>
                </div>
              </template>

              <!-- {{ key + ':' + state.serchValue[key] }} -->
            </div>

            <div class="serch_item">
              <!-- 日期  -->
              <a-range-picker @change="timeChange" format="YYYY-MM-DD" style="width: 229px" v-model:value="state.time"
                show-time />
            </div>

            <a-button type="primary" :loading="state.serchLoding" @click="getHumanVideoList">查询</a-button>
            <a-button :loading="state.serchLoding" @click="resetSerch">重置</a-button>
          </div>
        </div>

        <!-- 卡片形式的列表 -->

        <div class="cart_list" v-if="state.dataSource.length">
          <div class="cart_item" v-for="item in state.dataSource" :key="item.id">

            <div class="cart_main">
              <EyeOutlined v-if="item?.status != 0" @click="toviewVideo(item)" class="EyeOutlined"></EyeOutlined>

              <template v-if="cardShowMain(item)?.type == 'img'">
                    <img :src="cardShowMain(item)?.img" alt="" />
                </template>
              <template v-else-if="cardShowMain(item)?.type == 'video'">
                <video :src="cardShowMain(item)?.video"></video>
              </template>
              <template v-else>
                <div class="empty_box">
                  <!-- 暂无封面或视频 -->
                  <a-empty description="暂无封面或视频" :image="Empty.PRESENTED_IMAGE_SIMPLE" style="margin: 0 auto"/>
                </div>
              </template>

              <div class="item_name_box">
                <span class="item_name">{{ item.name}}</span>
              </div>
            </div>
            <div class="cart_bottom" >
              <div class="msg_box" >
                <span style="color: var(--ss-primary-color);">进行中: {{ getStatusNumber({item, status:'进行中'}) }}</span>
                <span style="color: green;">成功: {{ getStatusNumber({item, status:'成功'}) }}</span>
                <span style="color: red;">失败: {{ getStatusNumber({item, status:'失败'}) }}</span>
              </div>
            </div>
          </div>
        </div>

        <div style="display: flex; padding: 20px 0;" v-else>
          <a-empty :image="state.simpleImage" style="margin: 0 auto"/>
        </div>

        <div class="smart_clip_content_pagination" v-if="state.dataSource.length > 0">
          <a-pagination :total="formState.total" v-model:current="formState.page" v-model:pageSize="formState.pageSize" show-less-items
            @change="getList" />
        </div>

      </div>
    </div>

    <!-- 保存素材文件夹 -->
  <MaterialsModule ref="materials" :requestType="true" jobCategory="videoSplit" :data="state.materialData"
    :material_type="'video'" :isFlaking="state.isFlaking" :visible="state.saveVisible" @selfRequest="selfRequest"
    @onCancel="state.saveVisible = false" />

  <!-- 分组预览 -->
  <HumanSyntheticRecord ref="HumanSyntheticRecordRef" :statusOptions="statusOptions"></HumanSyntheticRecord>
</template>

<style lang="less" scoped>

.subtitleCreat{
    // height: calc(100% - 37px);
    height: 100%;
    width: 100%;
    padding-bottom: 40px;
    // padding-top: 20px;

    .list_conent {
    height: 100%;
    // overflow-y: auto;
    padding-bottom: 50px;

    display: flex;
    flex-direction: column;
    .table {
      .video_cart {
        height: 90px;
        width: 90px;
        display: flex;
        align-items: center;
        justify-content: center;
        position: relative;
        cursor: pointer;
        transition: all 0.3s;
        border: 1px solid transparent;
        border-radius: 5px;

        &:hover {
          border-color: var(--ss-primary-color-hover);

          .EyeOutlined {
            opacity: 1;
          }

          &::after {
            opacity: 1;
          }

          // & .bottom_box {
          //   opacity: 1;
          // }
        }

        &::after {
          content: "";
          position: absolute;
          left: 0;
          top: 0;
          width: 100%;
          height: 100%;
          background: #0000004b;
          opacity: 0;
          transition: all 0.3s;
        }

        .EyeOutlined {
          position: absolute;
          left: 50%;
          top: 50%;
          transform: translate(-50%, -50%);
          transition: all 0.3s;
          opacity: 0;
          font-size: 22px;
          color: #fff;
          z-index: 2;

          &:hover {
            color: var(--ss-primary-color-hover);
          }
        }

        img {
          height: 100%;
          width: auto;
        }

        video {
          height: 100%;
          width: auto;
        }
      }
    }

    // table 头部的筛选
    .serch_title {
      display: flex;
      align-items: center;
      justify-content: space-between;
      gap: 20px;
      margin-top: 10px;
      margin-bottom: 20px;

      .serch_left {
        display: flex;
        gap: 0 10px;

        .serch_item {
          display: flex;
          justify-content: center;
          align-items: center;

          .left_prefix {
            padding: 0 25px;
            background-color: #ffffff;
            line-height: 30px;
            border: 1px solid #d9d9d9;
            border-right: none;
          }
        }
      }
    }

    // table 列表
    .cart_list{
      display: flex;
      flex-wrap: wrap;
      align-items: flex-start;
      gap: 20px 20px;
      padding: 8px 0;
      overflow-y: auto;
      overflow-x: hidden;
      &::-webkit-scrollbar {
            width: 8px; /* 滚动条的宽度 */
            height: 10px; /* 滚动条的高度，垂直滚动条可能用得上 */
            display: none;
        }
        &::-webkit-scrollbar-thumb {
            background: #888; /* 滑块的背景颜色 */
            border-radius: 10px; /* 滑块的圆角 */

        }
      

      .cart_item{
        background-color: #fff;
        // border: 1px solid #eee;
        box-shadow: 0 0 12px rgba(0, 0, 0, 0.06); /* 透明度调低更柔和 */

        position: relative;
        // max-width: 190px;

        .status_tag{
          position: absolute;
          left: 5px;
          top: 5px;
          z-index: 1;
          font-size: 12px;
          font-weight: bold;
        }
        .edit_ellip{
          position: absolute;
          z-index: 3;
          right: 5px;
          top: 5px;
          font-size: 28px;
          color: #fff;
          line-height: 1;
          font-weight: bold;
          cursor: pointer;

          .ellips_box{
            background: #0000004b;
            padding: 0 5px;
            border-radius: 8px;
          }
        }
        .cart_main{
          height: 280px;
          width: 190px;
          cursor: pointer;
          position: relative;
          overflow: hidden;

                  // name 遮罩层
        .item_name_box{
          position: absolute;
          bottom: 0;
          left: 0;
          width: 100%;
          padding: 2px 5px;
          background: #0000004b;
          .item_name{
              color: #fff;
              overflow: hidden;
              text-overflow: ellipsis;
              display: -webkit-box;
              -webkit-line-clamp: 1;
              -webkit-box-orient: vertical;
              width: auto;
            }
        }

          img{
            // height: 100%;
            width: 100%;
            object-fit: cover;
          }
          video{
            // height: 100%;
            width: 100%;
          }
          .empty_box{
            height: 100%;
            width: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
            // background-color: #00000017;
          }

          &::after{
          content: '';
          position: absolute;
          left: 0;
          top: 0;
          z-index: 2;
          background-color: transparent;
          opacity: 0;
          transition: all .3s;
          height: 100%;
          width: 100%;
        }
          &:hover{
          &::after{
            background-color: #00000056;
            opacity: 1;
          }

          .EyeOutlined{
            opacity: 1;
          }
          .query_res{
            opacity: 1;
          }
        }

        .EyeOutlined{
          position: absolute;
          z-index: 3;
          left: 50%;
          top: 50%;
          transform: translate(-50%, -50%);
          color: #fff;
          transition: all .3s;
          opacity: 0;
          font-size: 30px;
          &:hover{
            color: var(--ss-primary-color-hover);
          }
        }

        .query_res {
          position: absolute;
          left: 50%;
          top: 50%;
          transform: translate(-50%, -50%);
          transition: all 0.3s;
          opacity: 0;
          z-index: 3;
        }

        }
        .cart_bottom{
          width: 100%;
          background-color: #fff;
          padding: 5px 5px;
          border-top: 1px solid #eee;
          font-size: 12px;
          .msg_box{
            display: flex;
            justify-content: space-between;
            align-items: center;


          }
        }
      }
    }

      // 分页
  .smart_clip_content_pagination {
    display: flex;
    margin-top: 20px;
    justify-content: flex-end;
  }

  }

    // 分页
  .smart_clip_content_pagination {
    display: flex;
    margin-top: 20px;
    justify-content: flex-end;
  }
}
</style>